package com.jbl.ma.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jbl.commonutils.R;
import com.jbl.ma.entity.UserApply;
import com.jbl.ma.entity.UserApplyEvidence;
import com.jbl.ma.entity.UserReject;
import com.jbl.ma.entity.UserRejectReason;
import com.jbl.ma.service.UserApplyEvidenceService;
import com.jbl.ma.service.UserApplyService;
import com.jbl.ma.service.UserRejectReasonService;
import com.jbl.ma.service.UserRejectService;
import com.jbl.ma.vo.ApplyRejectVO;
import com.jbl.ma.vo.UserApplyQuery;
import com.jbl.ma.vo.UserApplyVo;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author jbl
 * @since 2020-12-11
 */

@CrossOrigin
@RestController
@RequestMapping("/ma/user-apply")
public class UserApplyController {
    @Autowired
    private UserApplyService userApplyService;
    @Autowired
    private UserApplyEvidenceService userApplyEvidenceService;
    @Autowired
    private UserRejectService rejectService;
    @Autowired
    private UserRejectReasonService rejectReasonService;

    @PostMapping("/saveOrUpdateApply")
    @Transactional
    @ApiOperation(value = "创建更新申请")
    public R saveOrUpdateApply(@RequestBody UserApplyVo vo) {
        String id = vo.getApplyId();
        //id为空，或者申请不是未审批状态，创建
        if(StringUtils.isEmpty(id) || vo.getIsVerified() != 0) {
            UserApply apply = new UserApply();
            apply.setTeacherNumber(vo.getTeacherNumber());
            apply.setIsVerified(0);
            boolean save = userApplyService.save(apply);
            if(save) {
                UserApplyEvidence evidence = new UserApplyEvidence();
                evidence.setApplyId(apply.getApplyId());
                evidence.setRole(vo.getRole());
                evidence.setContent(vo.getContent());
                userApplyEvidenceService.save(evidence);
            }
            else return R.error().message("添加申请失败！");
        } else {
            UserApplyEvidence evidence = userApplyEvidenceService.getById(vo.getApplyId());
            evidence.setRole(vo.getRole());
            evidence.setContent(vo.getContent());
            boolean update = userApplyEvidenceService.updateById(evidence);
            if(!update) return R.error().message("更新申请失败！");
        }
        return R.ok();
    }

    @ApiOperation(value = "通过用户id获取最新申请")
    @GetMapping("/getApplyByUserId")
    public R getApplyByUserId(String id) {
        //获取最新apply
        ApplyRejectVO vo = new ApplyRejectVO();
        QueryWrapper<UserApply> wrapper = new QueryWrapper<>();
        wrapper.eq("teacher_number",id);
        wrapper.orderByDesc("gmt_modified");
        wrapper.last("limit 1");
        List<UserApply> applyList = userApplyService.list(wrapper);
        UserApply apply = null;
        if(!applyList.isEmpty()) apply = applyList.get(0);

        //最新apply存在，将其对应的evidence和reject(如果有)赋值给vo
        if(apply != null) {
            BeanUtils.copyProperties(apply,vo);
            UserApplyEvidence evidence = userApplyEvidenceService.getById(apply.getApplyId());
            BeanUtils.copyProperties(evidence,vo);
            QueryWrapper<UserReject> rejectQueryWrapper = new QueryWrapper<>();
            rejectQueryWrapper.eq("apply_id",apply.getApplyId());
            UserReject reject = rejectService.getOne(rejectQueryWrapper);
            if(reject != null) {
                UserRejectReason reason = rejectReasonService.getById(reject.getRejectType());
                vo.setRejectReason(reason.getRejectReason());
            }
        }
        return R.ok().data("apply",vo);
    }

    @ApiOperation(value = "分页多条件课程列表")
    @PostMapping("list/{page}/{limit}")
    public R pageQuery(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,

            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit,

            @ApiParam(name = "userApplyQuery", value = "查询对象", required = false)
            @RequestBody(required = false) UserApplyQuery userApplyQuery) {

        Page<UserApply> pageParam = new Page<>(page, limit);
        List<UserApplyVo> collect = userApplyService.pageQuery(pageParam, userApplyQuery);
        long total = pageParam.getTotal();
        return R.ok().data("total", total).data("dataList", collect);
    }

    @GetMapping("/list")
    @ApiOperation("获取用户审核列表")
    public R list() {
        List<UserApplyVo> collect = userApplyService.getApplyList();
        return R.ok().data("dataList", collect);
    }

    @GetMapping("/{teacherNumber}")
    @ApiOperation("获取自己审核情况")
    public R get(@PathVariable("teacherNumber") String teacherNumber) {
        UserApplyVo userApplyVo = userApplyService.isVerified(teacherNumber);
        return R.ok().data("data", userApplyVo);
    }

    @GetMapping("/pass")
    @ApiOperation("通过申请")
    public R pass(String applyId) {
        boolean pass = userApplyService.pass(applyId);

        if (pass) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @PostMapping("/passbatch")
    @ApiOperation("批量通过申请")
    public R passBatch(@RequestBody List<String> applyIds) {
        boolean pass = userApplyService.passBatch(applyIds);
        if (pass) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @Transactional
    @PostMapping("/add")
    @ApiOperation("添加申请")
    public R add(UserApplyVo vo) {
        UserApply userApply = new UserApply();
        userApply.setTeacherNumber(vo.getTeacherNumber());
        userApply.setSchoolId(vo.getSchoolId());
        userApply.setIsVerified(0);
        userApplyService.save(userApply);
        UserApplyEvidence evidence = new UserApplyEvidence();
        evidence.setApplyId(userApply.getApplyId());
        evidence.setContent(vo.getContent());
        userApplyEvidenceService.save(evidence);

        return R.ok();
    }
}
